#!/bin/bash

function checkService(){
  echo -e '\033[32m【'$1'】. 检查 Nacos['$2'] 是否注册..\033[0m'
  local i=1
  local response=''
  until [[ $response == *$2* ]]
  do
    if [ $i -gt 1 ]
    then 
        sleep 5
        echo -n '>'
    fi 
    response=$(curl -s --location 'http://baseservice:8848/nacos/v1/ns/service/list?pageNo=0&pageSize=100&namespaceId=dev')
    ((i++))
  done
  echo $response
}

function checkNacos(){
  echo '检查 Nacos 服务是否zhengch..'
  local j=1
  local response=''
  until [[ $response == *accessToken* ]]
  do
    if [ $j -gt 1 ]
    then 
  	sleep 5
        echo -n '>'
    fi 
    response=$(curl -s --location --request POST 'http://baseservice:8848/nacos/v1/auth/users/login?username=nacos&password=nacos')
    ((j++))
  done

  echo $response
  #echo [[ $response == *accessToken* ]]
}

starttime=`date +'%Y-%m-%d %H:%M:%S'`
# 关闭 java
until [ -z "$(ps -ef | grep java | grep www)" ]
do
  echo "关闭运行中的 java 程序"
  ps -ef | grep java | grep www | grep -v grep | awk '{print "kill -9 "$2}'|sh
  sleep 10
done
echo 'java 服务关闭就绪'

# 判断 Nacos 运行情况
if [[ $(checkNacos) == *accessToken* ]]
then 
  echo "Nacos 可以访问了"
  
  nohup java -jar -Xmx256m -Xms128m /opt/www/java/job.jar > /dev/null 2>&1 & 
  checkService 1 app-job && echo 'app-job 注册成功..'
  nohup java -jar -Xmx512m -Xms128m /opt/www/java/user.jar > /dev/null 2>&1 & 
  checkService 2 user-service  && echo 'user-service 注册成功..'
  nohup java -jar -Xmx512m -Xms128m /opt/www/java/system.jar > /dev/null 2>&1 & 
  checkService 3 system-service && echo 'system-service 注册成功..'
  nohup java -jar -Xmx1024m -Xms128m /opt/www/java/course.jar > /dev/null 2>&1 & 
  checkService 4 course-service && echo 'course-service 注册成功..'
  nohup java -jar -Xmx256m -Xms128m /opt/www/java/gateway.jar > /dev/null 2>&1 & 
  checkService 5 app-gateway && echo 'app-gateway 注册成功..'
  nohup java -jar -Xmx256m -Xms128m /opt/www/java/sba.jar > /dev/null 2>&1 &
  checkService 6 app-sba && echo 'app-sba 注册成功..'
  nohup java -Dfile.encoding=UTF-8 -Dspring.config.location=/opt/www/java/kkFileView/application.properties -jar -Xmx256m -Xms128m /opt/www/java/kkFileView/kkFileView-4.3.0.jar --KK_FILE_DIR="/root/kkdata" > /root/logs/kkFileView/kkFileView.log 2>&1 & 
  echo '文件预览服务启动成功..'

else
  echo "Nacos 访问不了"
fi

endtime=`date +'%Y-%m-%d %H:%M:%S'`
start_seconds=$(date --date="$starttime" +%s);
end_seconds=$(date --date="$endtime" +%s);
echo "本次运行时间： "$((end_seconds-start_seconds))"s"
